import { ALI_OSS_PATH } from '@/config/path';
import { getClientListServer } from '@/servers/app-servers';
import { activeCategoryIdAtom, resultShowAtom, ResultShowItemType } from '@/store/home';
import { shouldFetchResultsAtom } from '@/store/work';
import { useAtom } from 'jotai';
import { useRef } from 'react';
export const useResultShow = () => {
    const [resultshow, setUseResultShow] = useAtom(resultShowAtom)
    // 使用 useRef 存储 setInterval 的 ID
    const intervalIdRef = useRef<NodeJS.Timeout | null>(null)
    // 当前选中的频道id
    const [activeCategoryId] = useAtom(activeCategoryIdAtom)
    // 使用 setShouldFetchResults 来更新布尔值
    const [, setShouldFetchResults] = useAtom(shouldFetchResultsAtom); 
    // 存储上一次的任务数组长度
    const previousLengthRef = useRef(0); 
    const getResultShow = async () => {
        const res = await getClientListServer(activeCategoryId)
        const { result_limit20 } = res.data
        result_limit20.forEach((item: ResultShowItemType) => {
            if (item.status !== "done") {
                item.origin_img_path = `${ALI_OSS_PATH}${item.origin_img_path}`;
            } else {
                item.result_json.forEach((resItem, index) => {
                    resItem.path = `${ALI_OSS_PATH}${resItem.path}`
                    resItem.targetInd = index
                })
                item.result_json = item.result_json.filter(resItem => !resItem.is_del);
            }
        })
        setUseResultShow(result_limit20)
        // 获取当前满足状态 ["wait", "pre_wait1", "pre_wait", "working"] 的任务数组
        const currentLength = result_limit20.filter((item: ResultShowItemType) => 
            ["wait", "pre_wait1", "pre_wait", "working"].includes(item.status)
        ).length;

        // 如果任务数量减少，更新 shouldFetchResults 为 true，触发结果列表接口
        if (currentLength < previousLengthRef.current) {
            console.log("任务状态数组长度减少，更新工作列表...");
            setShouldFetchResults(true); // 更新状态触发结果列表接口
        }

        // 更新上一次的任务数组长度
        previousLengthRef.current = currentLength;

        // 检查是否需要启动轮询
        const shouldPoll = result_limit20.some((item: ResultShowItemType) =>  ["wait", "pre_wait1", "pre_wait", "working"].includes(item.status) );
        console.log("shouldPoll" , shouldPoll , !intervalIdRef.current);
        
        if (shouldPoll && !intervalIdRef.current) {
            // 如果满足条件，并且没有启动轮询，则启动 setInterval
            intervalIdRef.current = setInterval( getResultShow, 18000); // 每 18 秒调用一次 getResultShow
        } else if (!shouldPoll && intervalIdRef.current) {
            // 如果不再满足条件，清除定时器
            clearInterval(intervalIdRef.current);
            intervalIdRef.current = null;

            // 如果轮询结束，任务都完成，将 shouldFetchResults 设置为 true 触发工作列表更新
            setShouldFetchResults(true);
        }
    }
    return { getResultShow }
}